/**
 * Created by zhulizhe on 2017/8/17.
 */
'use strict';

import React, {Component,PropTypes} from 'react';
import {
    Text,
    View,
    TouchableWithoutFeedback,
    Image,
    Dimensions,
    ScrollView,
    Animated
} from 'react-native';
import Contant from "../Contant";

// 屏幕宽度
var screenWidth = Dimensions.get('window').width;

class ViewPager extends Component{
    constructor(props) {
        super(props);
        let images = this.props.images ;
        let imageHeight = this.props.imageHeight ;
        if(images==null){
            images = [] ;
        }
        if(imageHeight==null){
            imageHeight=140
        }
        this.state = {
            images : images,// 使用颜色代替图片
            selectedImageIndex: 0,
            isNeedRun: true,
            imageHeight:imageHeight
        };

        this._index = 0;// 当前正在显示的图片
        this._max = this.state.images.length;// 图片总数
        this.click = this.props.click ;
    }

    _onClick(i){
        if(this.click!=null)this.props.click(i);
    }

    render(){
        // 图片列表
        let images = this.state.images.map((value,i) => {
            return (
                <TouchableWithoutFeedback key={i} onPress={this._onClick.bind(this,i)}>
                    <Image style={{width:screenWidth,height:this.state.imageHeight,resizeMode:'contain'}} source={value}/>
                </TouchableWithoutFeedback>);
        });

        // 小圆点指示器
        let circles = this.state.images.map((value,i) => {
            return (<View
                key={i} style={ (i == this.state.selectedImageIndex) ? styles.circleSelected : styles.circle}/>);
        });

        // 小圆点位置居中显示
        let imageLength = this.state.images.length;
        let circleLength = 6 * imageLength + 5 * 2 * imageLength;
        let center = (screenWidth - circleLength) / 2;

        return (
            <View style={styles.container}>
                <ScrollView horizontal={true}
                            pagingEnabled={true}
                            showsHorizontalScrollIndicator={false}
                            showsVerticalScrollIndicator={false}
                            onTouchStart={()=>this._onTouchStart.bind(this)}
                            onTouchMove={()=>console.log('onTouchMove')}
                            onTouchEnd={()=>this._onTouchEnd.bind(this)}
                            onScroll={()=>this._onScroll.bind(this)}
                            ref={(scrollView) => { this._scrollView = scrollView;}}>

                    <Animated.View style={{flexDirection:'row'}}>{images}</Animated.View>
                </ScrollView>
                {
                    imageLength==1?(null):<View style={{flexDirection:'row',position:'absolute',bottom:10,left:center}}>{circles}</View>
                }
            </View>
        );
    }

    _onTouchStart(){
        // 当手指按到scrollview时停止定时任务
        clearInterval(this._timer);
    }

    _onTouchEnd(){
        // 先滑动到指定index位置，再开启定时任务
        this._scrollView.scrollTo({x:this._index * screenWidth},true);
        // 重置小圆点指示器
        this._refreshFocusIndicator();
        this._runFocusImage();
    }

    _onScroll(){
        this._contentOffsetX = this._scrollView.contentOffset.x;
        this._index = Math.round(this._contentOffsetX / screenWidth);
    }

    _runFocusImage(){
        if(this._max <= 1){ // 只有一个则不启动定时任务
            return;
        }
        this._timer = setInterval(function () {
            this._index++;
            if(this._index >= this._max){
                this._index = 0;
            }
            this._scrollView.scrollTo({x:this._index * screenWidth},true);
            // 重置小圆点指示器
            this._refreshFocusIndicator();
        }.bind(this), 4000);
    }

    _refreshFocusIndicator(){
        this.setState({selectedImageIndex:this._index});
    }

    // 组件装载完成
    componentDidMount(){
        this._runFocusImage();
    }

    // 组件即将卸载
    componentWillUnmount(){
        clearInterval(this._timer);
    }
}

const styles = {
    container: {
        flexDirection:'row',
        backgroundColor:'white'
    },
    circleContainer: {
        position:'absolute',
        left:0,
        top:120,
    },
    circle: {
        width:6,
        height:6,
        borderRadius:6,
        backgroundColor:'#fff',
        marginHorizontal:5,
    },
    circleSelected: {
        width:6,
        height:6,
        borderRadius:6,
        backgroundColor:Contant.BLUECOLOR,
        marginHorizontal:5,
    }
};

ViewPager.defaultProps = {
    isNeedRun : true,
};

ViewPager.propTypes = {
    isNeedRun   : PropTypes.bool,
    onItemClick : PropTypes.func,
};

module.exports = ViewPager;

